package me.shurufa.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.bean.UserInfoEntity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.fragments.TACommentFragment;
import me.shurufa.fragments.TADigestFragment;
import me.shurufa.utils.Constants;
import me.shurufa.utils.StatusBarCompat;
import me.shurufa.utils.Utils;
import me.shurufa.widget.CircleImageView;

public class NewUserCenterActivity extends AppCompatActivity implements View.OnClickListener {

    @Bind(R.id.back)
    ImageView mBackIv;

    @Bind(R.id.toolbar_title)
    TextView mTitleTv;

    @Bind(R.id.avatar)
    CircleImageView mAvatarIv;

    @Bind(R.id.viewpager)
    ViewPager mViewPager;

    @Bind(R.id.tabs)
    SlidingTabLayout mTabLayout;

    private boolean mSelectedDigest;
    private boolean mTypeMe;
    private UserInfoEntity mUserInfoEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_user_center);
        StatusBarCompat.setColor(this, getResources().getColor(R.color.red_new), 0);
        ButterKnife.bind(this);
        parseArguments();

        initViews();
        setupToolbar();
        setupViewPager();
        setupCollapsingToolbar();
    }

    private void initViews() {
        try {
            String nickname = mUserInfoEntity.username;
            mTitleTv.setText(nickname);
            mBackIv.setOnClickListener(this);

            loadImage();
        } catch (Exception e) {
            Utils.showToast(R.string.sys_err);
        }
    }

    private void loadImage() {
        if (!TextUtils.isEmpty(mUserInfoEntity.avatar)) {
            //加载头像
            Glide.with(this)
                    .load(mUserInfoEntity.avatar + Constants.THUMB_SUFFIX_AVATAR)
                    .asBitmap()
                    .centerCrop()
                    .placeholder(R.drawable.ic_def_avatar)
                    .into(new BitmapImageViewTarget(mAvatarIv) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    mAvatarIv.setImageDrawable(circularBitmapDrawable);
                }
            });
        } else {
            mAvatarIv.setImageResource(R.drawable.ic_def_avatar);
        }

    }

    /**
     *
     * @param in
     * @param selectDigestTab true为选中书摘的Tab， false为选中书评的Tab
     */
    public static void initArguments(Intent in, UserInfoEntity userInfoEntity, boolean selectDigestTab) {
        in.putExtra(Constants.ARG_SELECT_TAB, selectDigestTab);
        in.putExtra(Constants.ARG_USER_INFO, userInfoEntity);
    }

    private void parseArguments() {
        mSelectedDigest = getIntent().getBooleanExtra(Constants.ARG_SELECT_TAB, false);
        mUserInfoEntity = (UserInfoEntity) getIntent().getSerializableExtra(Constants.ARG_USER_INFO);

        try {
            mTypeMe = mUserInfoEntity.id == Long.valueOf(PersistenceUtils.getUserId());
        } catch (Exception e) {}
    }

    private void setupCollapsingToolbar() {
        final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);
        collapsingToolbar.setTitleEnabled(false);
    }

    private void setupViewPager() {
        setupViewPager(mViewPager);
        mTabLayout.setViewPager(mViewPager);
        setPagerItem(mSelectedDigest ? 0 : 1);
    }

    private void setupToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        // getSupportActionBar().setTitle("TabbedCoordinatorLayout");
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        // adapter.addFragment(TADigestFragment.newInstance(mUserInfoEntity), getString(mTypeMe ? R.string.my_digest : R.string.ta_digest));
        // adapter.addFragment(TACommentFragment.newInstance(mUserInfoEntity), getString(mTypeMe ? R.string.my_comment : R.string.ta_comment));
        adapter.addFragment(TADigestFragment.newInstance(mUserInfoEntity), getString(R.string.ta_digest));
        adapter.addFragment(TACommentFragment.newInstance(mUserInfoEntity), getString(R.string.ta_comment));
        viewPager.setAdapter(adapter);
    }

    private void setPagerItem(int item){
        mViewPager.setCurrentItem(item);
        // mTabLayout.setScrollPosition(item, 0, true);
        mTabLayout.setCurrentTab(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    static class ViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}
